<template>
  <div>
    <ContentHeader :title="store.lesson.title + ' - 资料管理'" v-if="store.lesson">
      <template #title>
        <el-button type="primary" size="small" @click="handleUpload">
          <el-icon><Plus /></el-icon>
          上传新资料
        </el-button>
      </template>
    </ContentHeader>
    <ContentBody v-loading="store.loading">
      <el-table :data="store.ebooks" :stripe="true" :highlight-current-row="true">
        <el-table-column property="id" width="80" />
        <el-table-column property="title" label="资料名称" />
        <el-table-column
          property="file"
          label="资料地址"
          :formatter="(row: any) => cfg.fileUrl(row.file)"
        />
        <el-table-column property="onself" label="上/下架">
          <template #default="scope">
            <el-switch v-model="scope.row.onself" @change="handleOnself" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button plain @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentBody>
    <FileUpload
      :lessonId="store.lesson.id"
      :limit="3"
      v-model="showUpload"
      v-if="store.lesson"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUpdated } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Plus, Delete } from '@element-plus/icons-vue'
import { useEbookStore } from '@/stores/ebook'
import { ElMessage, ElMessageBox } from 'element-plus'
import FileUpload from './upload.vue'
import cfg from '@/config/config'
import type { EbookItem } from '@/config/types'

const store = useEbookStore()
const router = useRouter()
const route = useRoute()
const showUpload = ref(false)

const handleUpload = () => {
  showUpload.value = true
}

const handleOnself = (val: boolean) => {
  store.updateOnself(val)
}

const handleDelete = (item: EbookItem) => {
  ElMessageBox.confirm('确定要删除' + item.title + '吗？', '确定删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    const result = await store.deleteEbook(item.id)
    if (result) {
      ElMessage.success('删除成功')
      store.loadEbooks(parseInt(route.params.lessonId as string))
    }
  })
}

const handleSuccess = () => {
  store.loadEbooks(parseInt(route.params.lessonId as string))
}

onMounted(() => {
  if (route.params.lessonId) {
    store.loadEbooks(parseInt(route.params.lessonId as string))
  } else {
    ElMessage.error('参数错误')
    router.back()
  }
})

onUpdated(() => {
  if (
    store.lesson &&
    route.params.lessonId &&
    store.lesson.id !== parseInt(route.params.lessonId as string)
  ) {
    store.loadEbooks(parseInt(route.params.lessonId as string))
  }
})
</script>
